package com.example.forum.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.forum.commons.authrization.TokenManager;
import com.example.forum.commons.tools.StringUtil;
import com.example.forum.commons.tools.Transfer.DataTransfer;
import com.example.forum.entity.TDatadictionaries;
import com.example.forum.service.ITDatadictionariesService;
import com.example.forum.service.ITPermissionsService;
import com.example.forum.vo.DataDictionaryModel;
import com.example.forum.vo.JsonResult;
import com.example.forum.vo.TreeDicationaryModel;
import com.example.forum.vo.TreeNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>String[]
 *
 * @author why
 * @since 2019-10-30
 */

@RestController
@Api(tags = "数据字典")
@RequestMapping("/DataDictionary")
public class TDatadictionariesController extends  BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TDatadictionariesController.class);

    @Autowired
    private ITPermissionsService permissionsService;
    @Autowired
    DataTransfer dataTransfer;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private ITDatadictionariesService dataDictionaryService;


    @ApiOperation(value = "更新数据字典")
    @PostMapping(value = "/update")
    public JsonResult update(
            @RequestBody @ApiParam(name = "数据字典对象", value = "传入json格式", required = true) DataDictionaryModel model) {
        var dto = dataDictionaryService.getById(model.getId());
        dto.setName(model.getName());
        dto.setValue(model.getValue());
        dataDictionaryService.updateById(dto);
        return new JsonResult(HttpStatus.OK, "更新成功", null);
    }


    @ApiOperation(value = "添加数据字典")
    @PostMapping(value = "/Add")
    public JsonResult Add(
            @RequestBody @ApiParam(name = "数据字典对象", value = "传入json格式", required = true) DataDictionaryModel model) {
        LOGGER.info("添加数据字典");

        if (StringUtil.isEmpty(model.getName())) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "数据字典名不能为空", null);
        }

        var dataDictionaries = dataDictionaryService.list(new QueryWrapper<TDatadictionaries>()
                .eq("name",  model.getName()).eq("ParentId", model.getParentId()));

        if (dataDictionaries != null && dataDictionaries.size() > 0) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "数据字典已存在", null);

        }
        var dto = new TDatadictionaries();
        dto = (TDatadictionaries) dataTransfer.getObjectFromObject(dto, model);

        dataDictionaryService.save(dto);
        var dataDictionary = dataDictionaryService.getOne(new QueryWrapper<TDatadictionaries>()
                .eq("name",  model.getName()).eq("ParentId", model.getParentId()));
        return new JsonResult(HttpStatus.OK, "成功", dataDictionary.getId());
    }


    @ApiOperation(value = " 根据Id数据字典。200获取成功")
    @GetMapping(value = "/GetDictionaryById")
    public JsonResult GetDictionaryById(String id) {
        LOGGER.info("获取数据字典");
        var result = dataDictionaryService.getById(id);
        return new JsonResult(HttpStatus.OK, "成功 ", result);
    }


    @ApiOperation(value = " 根据名称获取")
    @GetMapping(value = "/getDicByExpr")
    public JsonResult getDicByExpr(String expression) {
        LOGGER.info("获取数据字典");
        if (StringUtil.isEmpty(expression)) {

            return new JsonResult(HttpStatus.BAD_REQUEST, "名称不能为空 ", null);
        }
        var result = dataDictionaryService.findByExpression(expression);
        return new JsonResult(HttpStatus.OK, "成功 ", result);
    }


    @ApiOperation(value = " 根据名称获取")
    @GetMapping(value = "/getDicByName")
    public JsonResult getDicByName(String pid, String name) {
        var result = dataDictionaryService.findByName(pid, name);
        return new JsonResult(HttpStatus.OK, "成功 ", result);
    }

    @ApiOperation(value = "添加数据字典树")
    @PostMapping(value = "InsertTree")
    public JsonResult InsertTree(String pid, String name) {
        var dictions = dataDictionaryService.getOne(new QueryWrapper<TDatadictionaries>()
                .eq("parentId", pid)
                .eq("isdeleted", 0)
                .like("name", name));
        if (dictions != null) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "数据字典已存在", null);
        }
        var dictionaryDto = new TDatadictionaries();
        dictionaryDto.setParentid(pid);
        dictionaryDto.setName(name);
        dictionaryDto.setSort(0);
        dataDictionaryService.save(dictionaryDto);
        return new JsonResult(HttpStatus.OK, "添加成功", null);
    }


    @ApiOperation(value = "加载树")
    @GetMapping(value = "/LoadTree")
    public JsonResult LoadTree() {
        var treeNodes = new ArrayList<TreeNode>();
        var treeNodesResults = new ArrayList<TreeNode>();
        var result = dataDictionaryService.GetAllDataDicForTree();
        var AllresultP =dataDictionaryService.list(new QueryWrapper<TDatadictionaries>().isNull("parentId"));

        if (result != null && result.size() > 0) {
            result.forEach(temp -> {
                Map map = (Map) temp;
                var treeNode = new TreeNode();
                treeNode.setShowEdit(false);
                treeNode.setShowRemove(false);
                treeNode.setId(map.get("id").toString());
                treeNode.setParentid(map.get("ParentId") == null ? "0" : map.get("ParentId").toString());
                treeNode.setPermissionId(map.get("Name").toString());
                treeNode.setParentid(Integer.parseInt(map.get("ChildrenNumber").toString()) > 0 ? "true" : "false");
                treeNodes.add(treeNode);
            });
        }

        if (AllresultP.size() > 0 && AllresultP != null && AllresultP.size() > 0) {
            AllresultP.forEach(temp -> {
                var treeNode = new TreeNode();
                treeNode.setShowEdit(false);
                treeNode.setShowRemove(false);
                treeNode.setId(temp.getId());
                treeNode.setParentid(temp.getParentid());
                treeNode.setName(temp.getName());
                treeNode.setIsParent("true");
                var children = treeNodes.stream().filter((m) -> m.getId().equals(temp.getId())).findFirst().get();
                if (children != null) {
                    treeNode.setPermissionId(children.getPermissionId());
                    treeNode.setCheck(children.getCheck());
                } else {
                    return;
                }
                CreateTreeView(treeNodes, treeNode);
                treeNodesResults.add(treeNode);
            });
        }
        return new JsonResult(HttpStatus.OK, "加载成功", treeNodesResults);
    }

    /**
     * 循环创建树
     *
     * @param TreeNodes
     * @param treeModel
     */
    private void CreateTreeView(List<TreeNode> TreeNodes, TreeNode treeModel) {
        List<TreeNode> children = TreeNodes.stream()
                .filter((m) -> m.getParentid() != null && m.getParentid().equals(treeModel.getId()))
                .sorted(Comparator.comparing(TreeNode::getSort)).collect(Collectors.toList());
        if (children.size() == 0) {
            treeModel.children = children;
        }
        treeModel.children = new ArrayList<TreeNode>();
        children.forEach(temp -> {
            treeModel.children.add(temp);
            CreateTreeView(TreeNodes, temp);
        });
    }

    /**
     * 递归树结构
     *
     * @param TreeNodes
     * @param treeModel
     */
    private void CreateTreeDataDicView(List<TreeDicationaryModel> TreeNodes, TreeDicationaryModel treeModel) {
        List<TreeDicationaryModel> children = TreeNodes.stream()
                .filter(m -> m.getParentid() != null && m.getParentid().equals(treeModel.getId()))
                .sorted(Comparator.comparing(TreeDicationaryModel::getSort)).collect(Collectors.toList());
        if (children.size() == 0) {
            treeModel.childrens = null;
        }
        treeModel.childrens = new ArrayList<TreeDicationaryModel>();
        children.forEach(item -> {
            treeModel.childrens.add(item);
            CreateTreeDataDicView(TreeNodes, item);
        });
    }

    /**
     * 加载所有
     */
    @ApiOperation(value = "加载所有")
        @GetMapping(value = "/GetDataDicAll")
    public JsonResult GetDataDicAll() {
        var datadics = dataDictionaryService.list(new QueryWrapper<TDatadictionaries>().eq("isdeleted",0).orderByAsc("Sort"));
        var Outmodels = new ArrayList<TreeDicationaryModel>();
        var OutmodelResults = new ArrayList<TreeDicationaryModel>();
        var baseDics = dataDictionaryService.list(new QueryWrapper<TDatadictionaries>().eq("isdeleted",0).isNull("parentId"));
        datadics.forEach(datadic -> {
            var old = new TreeDicationaryModel();
            old = (TreeDicationaryModel) dataTransfer.getObjectFromObject(old, datadic);
            Outmodels.add(old);
        });
        if (baseDics != null) {
            baseDics.forEach(m -> {
                var old = new TreeDicationaryModel();
                old = (TreeDicationaryModel) dataTransfer.getObjectFromObject(old, m);
                CreateTreeDataDicView(Outmodels, old);
                OutmodelResults.add(old);

            });
        }
        return new JsonResult(HttpStatus.OK, "加载成功", OutmodelResults);
    }

    @ApiOperation(value = " 分页获取数据字典列表。200获取成功")
    @GetMapping(value = "/NodeView")
    public JsonResult NodeView(String pid, String Name, Integer pageIndex) {
        LOGGER.info("获取数据字典");
        Page<TDatadictionaries> page = new Page();
        page.setCurrent(pageIndex);
        page.setSize(10);
        IPage<TDatadictionaries> result = dataDictionaryService.page(page,new QueryWrapper<TDatadictionaries>().
                eq("parentId", pid).like("name", Name));
        return new JsonResult(HttpStatus.OK, "获取数据字典 ", result);
    }


    @ApiOperation(value = "删除数据字典")
    @PostMapping(value = "/delete")
    public JsonResult delete(String dataDicId) {
        LOGGER.info("删除数据字典");
        var pdto = dataDictionaryService.getById(dataDicId);
        if (pdto == null) {
            return new JsonResult(HttpStatus.NOT_FOUND, "该数据字典不存在", null);
        } else {
            pdto.setIsdeleted(true);
            pdto.setDeleteruserid(currentUserId());
            dataDictionaryService.updateById(pdto);
            return new JsonResult(HttpStatus.OK, "删除成功", null);
        }
    }

}

